<template>
  <div class="exam-container">
    <el-skeleton :loading="isFirst" :rows="15" animated>
      <div class="head-content-search">
        <div style="display: flex">
          <div class="exam-top-addbtn">
            <el-button size="small" v-if="params == '-1'" type="primary" @click="addQuestion" plain
              >新增试题</el-button
            >
            <!-- dialogTableVisible -->
            <el-button size="small" v-if="params != '-1'" type="primary" @click="importQuestions"
              >导入试题</el-button
            >
          </div>

          <!-- 搜索框 -->
          <div class="mySearch" style="flex: 1">
            <el-input
              :width="150"
              v-model="key"
              placeholder="请输入你要查询的题干名称"
              class="input-with-select"
            >
              <template #append>
                <el-button :icon="Search" />
              </template>
            </el-input>
          </div>

          <div class="myTips">
            <el-checkbox-group v-model="chosen" @change="checkStatus">
              <el-checkbox label="IsBan1">启用</el-checkbox>
              <el-checkbox label="IsBan2">禁用</el-checkbox>
              <el-checkbox label="IsPublish3">发布</el-checkbox>
              <el-checkbox label="IsPublish4">未发布</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>

        <div style="margin-top: 10px">
          <el-table :data="data" v-loading="isLoad" :border="true">
            <el-table-column label="复选框" type="selection" width="40px"></el-table-column>

            <el-table-column label="序号" type="index" width="60px"></el-table-column>
            <el-table-column
              label="题干"
              prop="content"
              :show-overflow-tooltip="true"
              class="last_commoner"
            >
            </el-table-column>
            <el-table-column label="类型" prop="type" width="100">
              <template #default="scope">
                <el-tag type="primary" size="small">
                  {{ scope.row.type == 1 ? '选择题' : '主观题' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="难度" prop="lv" width="60px"></el-table-column>
            <el-table-column
              label="使用"
              prop="useCount"
              width="80px"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                <el-tag type="primary" size="small">{{ scope.row.useCount }}次</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="发布" prop="isPublish" width="60">
              <template #default="scope">
                <!-- 1.已经发布 0.没有发布 -->
                <el-tag type="success" size="small" v-if="scope.row.isPublish == 1">是</el-tag>
                <el-tag type="danger" size="small" v-if="scope.row.isPublish == 0">否</el-tag>
              </template>
            </el-table-column>

            <el-table-column
              label="作者"
              prop="author"
              :show-overflow-tooltip="true"
              width="100"
            ></el-table-column>

            <el-table-column
              label="标签"
              prop="labels"
              :show-overflow-tooltip="true"
              width="100"
            ></el-table-column>

            <el-table-column label="禁用" prop="isBan" width="60">
              <template #default="scope">
                <!-- 1.禁用 0.没禁用 -->
                <el-tag type="danger" size="small" v-if="scope.row.isBan == 1">是</el-tag>

                <el-tag type="success" size="small" v-if="scope.row.isBan == 0">否</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="添加时间"
              prop="createTime"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column label="操作" fixed="right" width="350">
              <template #default="scope">
                <!-- 默认试题按钮 -->
                <el-button
                  type="primary"
                  size="small"
                  @click="questionsdetail(scope.row)"
                  :loading="btnLoad"
                  >详情</el-button
                >

                <!-- 启用 -->
                <el-button
                  type="success"
                  size="small"
                  plain
                  @click="IsBan(scope.row, 0)"
                  v-if="scope.row.isBan == 1 && scope.row.isPublish == 1"
                  :loading="btnLoad"
                  >恢复</el-button
                >
                <!-- 禁用 -->
                <el-popconfirm
                  title="确认禁用吗?"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  @confirm="IsBan(scope.row, 1)"
                >
                  <template #reference>
                    <el-button
                      type="danger"
                      size="small"
                      plain
                      v-if="scope.row.isBan == 0 && scope.row.isPublish == 1 && params == '-1'"
                      :loading="btnLoad"
                      >禁用</el-button
                    >
                  </template>
                </el-popconfirm>

                <!-- 移除 -->
                <el-popconfirm
                  title="确认从题库移除该试题吗?"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  @confirm="removeQuestion(scope.row)"
                >
                  <template #reference>
                    <el-button
                      type="danger"
                      size="small"
                      plain
                      v-if="params != '-1'"
                      :loading="btnLoad"
                      >移除</el-button
                    >
                  </template>
                </el-popconfirm>

                <!-- 删除 -->
                <el-popconfirm title="确认要删除吗?" @confirm="del(scope.row)">
                  <template #reference>
                    <el-button
                      type="danger"
                      size="small"
                      v-if="scope.row.isPublish == 0 && scope.row.useCount == 0"
                      :loading="btnLoad"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>

                <!-- 发布 -->
                <el-popconfirm
                  title="确认要发布吗?"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  @confirm="IsPublish(scope.row, 1)"
                >
                  <template #reference>
                    <el-button
                      type="success"
                      size="small"
                      v-if="scope.row.isPublish == 0"
                      :loading="btnLoad"
                      >发布</el-button
                    >
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div
            style="
              margin-top: 10px;
              padding-bottom: 10px;
              display: flex;
              justify-content: space-between;
              border: 1px solid #eee;
            "
          >
            <el-pagination
              background
              @size-change="changLimit"
              layout="sizes,prev, pager, next"
              :total="total"
              small
              style="margin: 10px 0 0 10px"
              v-model:current-page="page"
              :page-sizes="[10, 20, 30, 40, 50]"
            />

            <el-tag size="small" type="info" style="margin: 14px 10px 0 0"
              >Tips:暂不提供修改试题的功能,如果需要修改,请删除后重新添加！</el-tag
            >
          </div>
        </div>
      </div>
    </el-skeleton>
  </div>





  <div>
    <div class="dialog_bigbox">
      <el-dialog v-model="dialogTableVisible"  fullscreen title="导入试题">
        <el-skeleton :loading="tisFirst"  :rows="15" animated>
          <div class="dialog_box">
            <div class="header">
              <div>
                <div class="btn_import">
                  <el-button
                    size="small"
                    type="primary"
                    @click="addQuestion"
                    plain
                    >根据题库查询</el-button
                  >
                
                </div>

                <!-- 搜索框 -->
                <div class="mySearch_import">
                  <el-input
                    :width="150"
                    v-model="tKey"
                    placeholder="请输入你要查询的题干名称"
                    class="input-with-select"
                  >
                    <template #append>
                      <el-button :icon="Search" />
                    </template>
                  </el-input>
                </div>

              </div>
            </div>
            <!-- @selection-change="handleSelectionChange" -->
            <div class="content_import">
              <el-table :data="tData"
               v-loading="tisLoad"
                :border="true"
                ref="multipleTableRef"
               
                :row-key="check_Row"
                @select-all="selectAll"
                @select="radio"
                >
            <el-table-column label="复选框" type="selection" width="40px"  :reserve-selection="true"></el-table-column>

            <el-table-column label="序号" type="index" width="60px"></el-table-column>
            <el-table-column
              label="题干"
              prop="content"
              :show-overflow-tooltip="true"
              class="last_commoner"
            >
            </el-table-column>
            <el-table-column label="类型" prop="type" width="100">
              <template #default="scope">
                <el-tag type="primary" size="small">
                  {{ scope.row.type == 1 ? '选择题' : '主观题' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="难度" prop="lv" width="60px"></el-table-column> 

            <el-table-column
              label="作者"
              prop="author"
              :show-overflow-tooltip="true"
              width="100"
            ></el-table-column>

            <el-table-column
              label="标签"
              prop="labels"
              :show-overflow-tooltip="true"
              width="100"
            ></el-table-column>

            <el-table-column
              label="添加时间"
              prop="createTime"
              :show-overflow-tooltip="true"
            ></el-table-column>

          </el-table>
          <el-tag size="small" type="info" style="margin: 10px 10px 0 0"
              >无试题选择限制,实际选择【{{select_orderId.length}}】道试题</el-tag
            >
          <!-- 分页 -->
          <div
            style="
              margin-top: 10px;
              padding-bottom: 10px;
              display: flex;
              justify-content: space-between;
              border: 1px solid #eee;
            "
          >
            <el-pagination
              background
              @size-change="tChangLimit"
              layout="sizes,prev, pager, next,total"
              :total="tTotal"
              small
              @current-change="changPage"
              style="margin: 10px 0 0 10px"
              v-model:current-page="tPage"
              :page-sizes="[10, 20, 30, 40, 50]"
            />
          
            <el-button type="primary"
             style=" margin-top: 10px;margin-right: 10px;" 
             plain
             @click="sureimport"
             >确认选择</el-button>
          </div>
            </div>
          </div>
        </el-skeleton>
      </el-dialog>
    </div>
  </div>

  
</template>
 <script lang="ts">
import { defineComponent, reactive, toRefs, watchEffect, ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import type { Question_IndexDto } from '@/dto/question/IndexDto'
import { useRoute, useRouter } from 'vue-router'
import {
  queryAllQuestion,
  TopicIsPublish,
  delQUestion,
  TopicIsBan,
  queryAllQuestionChecks,
  removeQuestion
} from '@/api/exam'
import getTime from '@/utils/getTime'
import { ElMessage, ElMessageBox } from 'element-plus'
import { openLoad, closeLoad } from '@/utils/loading'
import { importQuestions } from '../../../api/exam'

export default defineComponent({
  setup() {
    //参数获取常用
    const routes = useRoute()
    //路由跳转常用
    const router = useRouter()
    const dialogFormVisible = ref(false)
    const multipleTableRef = ref()
    const formLabelWidth = '140px'
    const tdata = reactive<any>({
      tisFirst:true,
      tisLoad:false,
      tIsBan: 0,
      tIsPublish: 1,
      tPage: 1,
      tTotal: 0,
      tLimit: 10,
      tData: [],
      selectionKeys: [],
      checkData:[],
      select_orderId:[],//表格select复选框选中的id
      tKey: '',
      tLabels: '',
      tExcludeQBID: routes.params.id,
      tBanks: '',
      tExcludeQIDs: [],
      tChapterids: '',
    })
    const data = reactive<Question_IndexDto>({
      dialogTableVisible: false,
      key: '',
      params: routes.params.id,
      checkList: [
        // { label: '启用', isBan: 0 },
        // { label: '禁用', isBan: 1 },
        // { label: '发布', IsPublish: 1 },
        // { label: '未发布', IsPublish: 0 }
      ],
      chosen: [],
      isBan: -1,
      isPublish: -1,
      page: 1,
      total: 0,
      limit: 10,
      data: [],
      terms: [],
      //表格加载效果
      isLoad: true,
      //屏骨架加载效果
      isFirst: true,
      //点击按钮加载效果
      btnLoad: false,
    })
    const events = {
      /**
       * 
       * @param selection 复选框回显使用的方法 start
       * @param row 
       */
      radio:(selection:any,row:any)=>{
        tdata.select_orderId=selection;
      },
     selectAll:(selection:any)=>{
            tdata.select_orderId=selection;
     },
      check_Row:(row:any)=>{
          return row.id;
      },
      /**
       * 
       * @param selection 复选框回显使用的方法  end
       * @param row 
       */


      //页码改变事件
      changPage:(val:any)=>{
         
      },
      /**
       * 选中框选中事件
       * @param rows 
       */
      handleSelectionChange (rows:any) {
      //选中的id
      tdata.select_orderId = rows.map((item:any) => item.id);
    },
      /**
       * 点击导入试题按钮触发 跳转到导入试题页面并加载好可倒入的数据
       */
      importQuestions: () => {
        data.dialogTableVisible = true;
        tdata.tisLoad=true;
        queryAllQuestion({
          page: tdata.tPage,
          limit: tdata.tLimit,
          isPublish: tdata.tIsPublish,
          isBan: tdata.tIsBan,
          key: tdata.tKey,
          labels: tdata.tLabels,
          excludeQBID: tdata.tExcludeQBID,
          banks: tdata.tBanks,
          excludeQIDs: tdata.excludeQIDs,
          chapterids: tdata.tChapterids
        }).then((res:any)=>{
             tdata.tData=res.data.data;
             tdata.tTotal=res.data.total;
             tdata.tisFirst=false;
             tdata.tisLoad=false;
        });
      },
      /**
       * 导入试题确认导入按钮点击事件
       */
      sureimport:()=>{
            ElMessageBox.confirm(`确认选择这${tdata.select_orderId.length}道题目吗？`).then(()=>{
              let ids=tdata.select_orderId.map((d:any)=>d.id)
              importQuestions({id:tdata.tExcludeQBID,ids:ids}).then((res:any)=>{
                if(res.result===0){
                 ElMessage.success(res.message)
                 setTimeout(() => {
                   data.dialogTableVisible = false;
                 }, 1000);
                }else{
                  ElMessage.error(res.message);
                }
               
              })
            
                     
            }).catch(()=>{})
      },
      /**
       * 查询默认题库试题的试题列表的题目详情
       * 参数:题目id
       */
      questionsdetail: (val: any) => {
        openLoad("请稍后");
        setTimeout(() => {
          closeLoad();
        }, 1000);
        router.push(`/exam/question/topicDetails/${val.id}`)
      },

      /**
       * 移除题库的试题列表的题目
       */
      removeQuestion: (val: any) => {
        data.isLoad=true;
        removeQuestion({ id: data.params, ids: [val.id] }).then((res: any) => {
          if (res.result === 0) {
            ElMessage.success('操作成功')
            events.getQuestion()
          } else {
            ElMessage.success('参数错误')
          }
        })
      },

      /**
       * 默认题库题目的禁用与恢复 传值1/0
       * @param val
       * @param num
       */
      IsBan: (val: any, num: number) => {
        data.isLoad = true
        TopicIsBan({ ids: [val.id], isBan: num }).then((res: any) => {
          if (res.result === 0) {
            ElMessage.success('操作成功')
            events.getQuestion()
          } else {
            ElMessage.success('参数错误')
          }
        })
      },

      /**
       * 删除默认题库题目
       * @param val
       */
      del: (val: any) => {
        data.isLoad = true
        delQUestion({ ids: [val.id] }).then((res: any) => {
          if (res.result === 0) {
            ElMessage.success('操作成功')
            events.getQuestion();
          } else {
            ElMessage.success('参数错误')
          }
        })
      },
      /**
       * 默认题库发布试题 0默认未发布 1为已发布状态
       * @param val
       * @param num
       */
      IsPublish: (val: any, num: number) => {
        data.isLoad = true;
        TopicIsPublish({ ids: [val.id], isPublish: num }).then((res: any) => {
          if (res.result == 0) {
            ElMessage.success('操作成功')
            events.getQuestion()
          } else {
            ElMessage.success('参数错误')
          }
        })
      },

      /**
       * 修改每页显示多少条信息
       */
      changLimit(val: any) {
        data.limit = val;
      },

      /**
       * 导入试题修改每页显示多少条信息
       */
       tChangLimit(val: any) {
        tdata.tLimit = val;
      },

      /**
       * 复选框事件
       */
      checkStatus: () => {
        data.page = 1
        let sz: any = data.chosen;
        data.terms = []
        if (sz.length > 2) {
          data.chosen?.shift()
        }

        sz.forEach((d: any, i: number) => {
          data.terms?.push(d.charAt(d.length - 1))
        })
        if (data.terms.includes('2') && data.terms.includes('3')) {
          //  console.log("查询已经发布的和已禁用");
          // events.queryAllQuestionChecks(1, 1)
          data.isPublish = 1
          data.isBan = 1
          events.getQuestion()
          return
        }

        if (data.terms.includes('2') && data.terms.includes('4')) {
          //  console.log("查询未发布的和已禁用");
          // events.queryAllQuestionChecks(0, 1)
          data.isPublish = 0
          data.isBan = 1
          events.getQuestion()
          return
        }

        if (data.terms.includes('1') && data.terms.includes('3')) {
          //  console.log("查询已发布的和启用");
          // events.queryAllQuestionChecks(1, 0)
          data.isPublish = 1
          data.isBan = 0
          events.getQuestion()
          return
        }

        if (data.terms.includes('1') && data.terms.includes('4')) {
          //  console.log("查询未发布的和启用");
          // events.queryAllQuestionChecks(0, 0)
          data.isPublish = 0
          data.isBan = 0
          events.getQuestion()
          return
        }

        if (data.terms.includes('1') && data.terms.includes('2')) {
          //  console.log("查询未发布的和发布");
          // events.getQuestion();
          data.isPublish = -1
          data.isBan = -1
          events.getQuestion()
          return
        }

        if (data.terms.includes('3') && data.terms.includes('4')) {
          //  console.log("查询未禁用的和禁用");
          // events.getQuestion();
          data.isPublish = -1
          data.isBan = -1
          events.getQuestion()
          return
        }

        if (data.terms.includes('3')) {
          //  console.log("查询已经发布的");
          // events.queryAllQuestionChecks(1, -1)
          data.isPublish = 1
          data.isBan = -1
          events.getQuestion()
          return
        }

        if (data.terms.includes('2')) {
          //  console.log("查询已经禁用的");
          // events.queryAllQuestionChecks(-1, 1)
          data.isPublish = -1
          data.isBan = 1
          events.getQuestion()
          return
        }

        if (data.terms.includes('4')) {
          //  console.log("查询未发布的");
          // events.queryAllQuestionChecks(0, -1)
          data.isPublish = 0
          data.isBan = -1
          events.getQuestion()
          return
        }

        if (data.terms.includes('1')) {
          //  console.log("查询已经启用的");
          // events.queryAllQuestionChecks(-1, 0)
          data.isPublish = -1
          data.isBan = 0
          events.getQuestion()
          return
        }

        data.isPublish = -1
        data.isBan = -1
        events.getQuestion()
      },

      /**
       * 获取当前页面满足勾选的复选框的默认题库试题的试题列表
       * @param IsPusblish 0为查询未发布 1未查询已经发布
       * @param IsBan 0查询为未禁用，1查询为已禁用   暂时废弃,使用getQuestion方法替代
       */
      queryAllQuestionChecks: (IsPusblish: any, IsBan: any) => {
        data.isLoad = true
        queryAllQuestionChecks({
          page: data.page,
          limit: data.limit,
          key: data.key,
          isPusblish: IsPusblish,
          isBan: IsBan
        }).then((res: any) => {
          setTimeout(() => {
            data.isLoad = false
            data.isFirst = false
            if (res.result == 0) {
              /**
               *时间戳改为现在时间
               */
              // res.data.data.map((d: any) => {
              //   // d.QCreateTime=events.timestampToTime(d.QCreateTime);
              //   d.QCreateTime = getTime.timestampToTime(d.QCreateTime)
              // })
              // console.log(res);
              // console.log(res.data);

              data.data = res.data.data
              data.total = res.data.total
            }
          }, 1500)
        })
      },

      /**
       * 默认题库的试题列表的数据加载
       */
      getQuestion: () => {
        if (data.params == '-1' || data.params == null || data.params == '') {
          data.isLoad = true
          queryAllQuestion({
            page: data.page,
            limit: data.limit,
            key: data.key,
            isBan: data.isBan,
            isPublish: data.isPublish
          }).then((res: any) => {
            setTimeout(() => {
              data.isLoad = false;
              data.isFirst = false;
              if (res.result === 0) {
                //与下方效果等同
                //   res.data.data.forEach((d:any,i:any)=> {
                //   res.data.data[i].QCreateTime=events.timestampToTime(d.QCreateTime)
                //  });

                // res.data.data.map((d: any) => {
                //   d.QCreateTime = getTime.timestampToTime(d.QCreateTime)
                // })
                data.data = res.data.data;
                data.total = res.data.total;
              }
            }, 1500)
          })
        } else {
          data.isLoad = true
          queryAllQuestion({
            page: data.page,
            limit: data.limit,
            key: data.key,
            isBan: data.isBan,
            isPublish: data.isPublish,
            banks: data.params
          }).then((res: any) => {
            setTimeout(() => {
              data.isLoad = false;
              data.isFirst = false;
              if (res.result === 0) {
                //与下方效果等同
                //   res.data.data.forEach((d:any,i:any)=> {
                //   res.data.data[i].QCreateTime=events.timestampToTime(d.QCreateTime)
                //  });

                // res.data.data.map((d: any) => {
                //   d.QCreateTime = getTime.timestampToTime(d.QCreateTime)
                // })
                data.data = res.data.data;
                data.total = res.data.total;
              }
            }, 1500)
          })
        }
      },

      /**
       * 添加试题
       */
      addQuestion: async () => {
        openLoad('请稍后')
        router.push('/exam/question/add')
        setTimeout(() => {
          closeLoad()
        }, 1500)
      }
    }
    
    
   onMounted(()=>{

   })
    
    watchEffect(() => {
      events.getQuestion();
      if(data.dialogTableVisible == true){
        // tdata.select_orderId=[];
        events.importQuestions();
      }

      if(tdata.dialogTableVisible == false){
        tdata.tisFirst=true;
      }

      // if(data.dialogTableVisible == false){
      //     tdata.tisFirst=true;
       
      // }
    //   const { selectionKeys, tData } = tdata;
    //   selectionKeys.forEach((key:any) => {
    //     tData.forEach((row:any) => {
    //     if (row.id == key) {
    //       this.$refs.multipleTable.toggleRowSelection(row, true);
    //     }
    //   })
    // })
  })

    return {
      ...toRefs(data),
      ...toRefs(tdata),
      ...events,
      Search,
      dialogFormVisible,
      multipleTableRef,
      formLabelWidth
    }
  }
})
</script>
 

<style scoped>
.question-head {
  border: 1px solid #eee;
  padding: 5px;
}

.dialog_box {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #eee;
  border-radius: 6px;
}

.header {
  margin: 10px;
  border: 1px solid #eee;
  height: 50px;
  line-height: 44px;
  border-radius: 6px;
}

.mySearch_import{
  width: 400px;
  margin: auto;
}

.btn_import{
  float: left;
  margin-left: 10px;
}

.content_import{
  margin: 10px;
}
</style>